package pri.hillchen.std;

import org.apache.zookeeper.ZooKeeper;
import pri.hillchen.std.simpledemo.javaapi.DistributeLock;
import pri.hillchen.std.simpledemo.javaapi.JavaApiDistributeLocak;
import pri.hillchen.std.simpledemo.javaapi.ZookeeperUtil;

import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 15:28 2018/3/12 0012.
 */
public class DistributeLockDemo {
    static class EndEntry{
        boolean end = false;
        void setEnd(){
            end = true;
        }
        public boolean isEnd() {
            return end;
        }
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        final EndEntry end = new EndEntry();
        String fileName = "C:\\temp\\zookeepertest\\locktest.txt";
        ZooKeeper zooKeeper = ZookeeperUtil.createClient();
        String lockName = "locktest";
        DistributeLock lock = new JavaApiDistributeLocak(zooKeeper);
        lock.lock(lockName,()->{
            String readLine = "";
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(fileName);
                while(!("stop\n").equals(readLine)){
                    byte[] bytes = new byte[512];
                    int writeNo = System.in.read(bytes);
                    readLine = new String(bytes,0,writeNo);
                    fileWriter.write(readLine);
                    fileWriter.flush();
                }
                fileWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                fileWriter.close();
                end .setEnd();
            }

        },()->{
            System.out.println("获取锁失败，进入锁等待");
        },(exception)->{
            System.out.println("执行获取锁异常，异常结束！");
            end .setEnd();
        });
        while (!end.isEnd()){
            TimeUnit.SECONDS.sleep(5);
        }

        TimeUnit.SECONDS.sleep(5);
    }
}
